//
//  UIWindow+ZZ.swift
//  StudyAsk
//
//  Created by CZZ on 2020/5/25.
//  Copyright © 2020 陈钟. All rights reserved.
//

import Foundation
import UIKit

public extension UIWindow{

    func visibleViewController() -> UIViewController?{
        guard let rootViewCtrl = keyWindow?.rootViewController else { return nil }
        return UIWindow.getVisibleViewController(from: rootViewCtrl)
    }

    static func getVisibleViewController(from viewCtrl: UIViewController) -> UIViewController{
        if viewCtrl is UINavigationController{
            guard let vc = (viewCtrl as! UINavigationController).visibleViewController else { return viewCtrl }
            let newVc =  UIWindow.getVisibleViewController(from: vc)
            if newVc.isBeingDismissed || newVc.isAlertBeingDismiss{
                return vc
            }
            return newVc
        }else if viewCtrl is UITabBarController{
            guard let vc = (viewCtrl as! UITabBarController).selectedViewController else { return viewCtrl }
            let newVc =  UIWindow.getVisibleViewController(from: vc)
            if newVc.isBeingDismissed || newVc.isAlertBeingDismiss{
                return vc
            }
            return newVc
        }else if (viewCtrl.children.count > 0 ){
            guard let vc = viewCtrl.children.last else { return viewCtrl }
            let newVc =  UIWindow.getVisibleViewController(from: vc)
            if newVc.isBeingDismissed || newVc.isAlertBeingDismiss{
                return vc
            }
            return newVc
        }
        if let vc = viewCtrl.presentedViewController {
            let newVc =  UIWindow.getVisibleViewController(from: vc)
            if newVc.isBeingDismissed || newVc.isAlertBeingDismiss{
                return vc
            }
            return newVc
        }
        return viewCtrl
    }

    /// 获取当前显示窗体
    static func getCurrentViewController() -> UIViewController?{
        guard var window = keyWindow else { return nil }
        if window.windowLevel != .normal{
            let windows = UIApplication.shared.windows
            for subWindow in windows{
                if subWindow.windowLevel == .normal{
                    window = subWindow
                    break
                }
            }
        }
        guard let appRootViewCtrl = window.rootViewController else { return nil }
        return UIWindow.getVisibleViewController(from: appRootViewCtrl)
    }
}
